package com.ita.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ita.entity.User;
import com.ita.service.IUserService;
import com.ita.service.impl.UserServiceImpl;

/**
 * Servlet implementation class DeleteByIdServlet
 */
public class DeleteByIdServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IUserService service=new UserServiceImpl();      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteByIdServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		deleteById(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		deleteById(request,response);
	}
	private void deleteById(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
//		String userId=request.getParameter("userId");
		
		String userId=request.getParameter("id");
		
		
		PrintWriter writer=response.getWriter();
		HttpSession session=request.getSession();
		User u=(User) session.getAttribute("loginToken");
		if(u.getUserId().equals(userId)){
			writer.write("<h1>you can not delete yourself</h1>");
		}
		else{
			List<User> list=new ArrayList<User>();
	    	boolean flag=service.deleteById(userId);
			if(flag){
				
				if(session.getAttribute("loginToken")!=null){
		    		List<User> list1=service.showAllUsers();
		    		for(User user:list1){
		    			list.add(user);
		    		}
		    	}
				request.setAttribute("list", list);
				request.getRequestDispatcher("alluser.jsp").forward(request, response);
			}
			else{
				writer.write("<h1>delete failed</h1>");
			}
		}
	}
}
